package rota.dao;


import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import rota.model.Contact;

@Repository
@Transactional
public class ContactDao implements IContactDao {
	
	@PersistenceContext
	private EntityManager entityManager;
	

	protected EntityManager getEntityManager() {
		return entityManager;
	}
	
	/**
	 * Salva e atualiza o objeto
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED,rollbackFor=Exception.class) // ou a grava��o no banco acontece em sua totalidade ou os dados sao descartados
	public void persistirConta(Contact obj) {
		if (obj.getId() == 0) {
			getEntityManager().persist(obj);
		} else {
			getEntityManager().merge(obj);
		}

		getEntityManager().flush(); //descarrega o buffer no banco
	}

	@Override
	public void addContact(Contact contact) {
		persistirConta(contact);
		
	}

	@Override
	public List<Contact> listContact() {
//		SELECT s FROM SalaBatePapo s
		String jpql = "SELECT c FROM Contact c";
		List <Contact>user;
		try {
			// Obtem o objeto gerado pela JPQL
			Query query = getEntityManager().createQuery(jpql);
			user = (List<Contact>) query.getResultList();
		} catch (Exception e) {
			System.out.println("Erro : " + e);
			user = null;
		}
		
		return user;
	}

	@Override
	public void removeContact(Integer id) {
		Contact user = buscaContactId(id);
		
		if(user!=null){
		getEntityManager().remove(user);
		}
		
	}
	public Contact buscaContactId(Integer id){
		String jpql="SELECT u FROM Contact u WHERE u.id = " + id;
		Contact user;
		try {
			// Obtem o objeto gerado pela JPQL
			Query query = getEntityManager().createQuery(jpql);
			user = (Contact) query.getSingleResult();
		} catch (Exception e) {
			System.out.println("Erro : " + e);
			user = null;
		}
		return user;
	}

}
